package itemControllers

import (
	"fmt"
	"lazyops_go/models"
	"lazyops_go/tasks"
	"lazyops_go/tools"
	"os"
	"path"
	"strings"
)

func (c *ItemController) IndexRelease() {
	role_id_list := c.GetSession("role_id_list").([]int)
	data_list := models.QueryReleaseAll(role_id_list)
	platfm_list := models.QueryPlatfmAll(role_id_list)
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_user := c.GetSession("cur_user")
	c.Data["cur_user"] = cur_user
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["platfm_list"] = platfm_list
	c.Data["label"] = "版本发布"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "items/releasejs.html"
	c.TplName = "items/release.html"
}

func (c *ItemController) SearchRelease() {
	key := c.Ctx.Input.Param(":key")
	data_list := models.QueryReleaseSearch(key)
	role_id_list := c.GetSession("role_id_list").([]int)
	platfm_list := models.QueryPlatfmAll(role_id_list)
	cur_user_menus := c.GetSession("cur_user_menus")
	cur_user := c.GetSession("cur_user")
	c.Data["cur_user"] = cur_user
	c.Data["key"] = key
	c.Data["cur_user_menus"] = cur_user_menus
	c.Data["data_list"] = data_list
	c.Data["platfm_list"] = platfm_list
	c.Data["label"] = "版本发布"
	c.XSRFExpire = 7200
	c.Data["xsrf_token"] = c.XSRFToken()
	c.Layout = "base/base.html"
	c.LayoutSections = make(map[string]string)
	c.LayoutSections["Scripts"] = "items/releasejs.html"
	c.TplName = "items/release.html"
}

func (c *ItemController) CreateRelease() {
	platfm_id, _ := c.GetInt("platfm_id", 0)
	release_host := c.GetString("release_host")
	proxy_host := c.GetString("proxy_host")
	obj := models.ItemRelease{}
	obj.PlatfmID = platfm_id
	obj.ReleaseHost = release_host
	obj.ProxyHost = proxy_host
	err := models.AddRelease(obj)
	if err != nil {
		c.Data["json"] = err
	} else {
		c.Data["json"] = "添加成功"
	}
	c.ServeJSON()
}

func (c *ItemController) GetIdRelease() {
	id, _ := c.GetInt("id", 0)
	data := models.QueryReleaseOne(id)
	c.Data["json"] = data
	c.ServeJSON()
}

func (c *ItemController) EditRelease() {
	id, _ := c.GetInt("id", 0)
	platfm_id, _ := c.GetInt("platfm_id", 0)
	release_host := c.GetString("release_host")
	proxy_host := c.GetString("proxy_host")
	obj := models.ItemRelease{}
	obj.PlatfmID = platfm_id
	obj.ReleaseHost = release_host
	obj.ProxyHost = proxy_host
	err := models.UpdateRelease(id, obj)

	if err != nil {
		c.Data["json"] = err
	} else {
		c.Data["json"] = "更新成功"
	}
	c.ServeJSON()
}

func (c *ItemController) DelRelease() {
	id, _ := c.GetInt("id", 0)
	err := models.DeleteRelease(id)
	if err != nil {
		c.Data["json"] = err
	} else {
		c.Data["json"] = "已删除"
	}
	c.ServeJSON()
}

func (c *ItemController) SyncVersion() {
	id, _ := c.GetInt("id", 0)
	obj := models.QueryReleaseOne(id)
	src_path := fmt.Sprintf("/data/smb/server/%s/%s/", obj.Platfm.Prj.PrjName, obj.Platfm.CodeVersion)
	src_package := src_path + "server.tar.gz"

	time_cmd := `ls --time-style "+%Y-%m-%d %H:%M:%S" -lct ` + src_package + "|grep -v ^total| awk '{print $6,$7}'"
	cat_cmd := fmt.Sprintf(`cat %sserver/ver/ver.txt | grep code | awk '{print $2}'|sed 's/}//'|sed 's/"//g' | grep -v ^$ |sed 's/,/\//'| sed  '1~2N;s/\r\n//'`, src_path)
	cmd := fmt.Sprintf("%s", cat_cmd)
	dict_obj, _ := models.QueryDictKey("RELEASE_HOST")
	release_host := dict_obj.DictVal
	ret := tools.SaltRunArgRet(release_host, "cmd.run", cmd, "root")
	up_time := tools.SaltRunArgRet(release_host, "cmd.run", time_cmd, "root")
	obj.CurVersion = ret
	obj.PackageTime = up_time
	models.UpdateRelease(id, obj)
	c.Data["json"] = "已同步"
	c.ServeJSON()
}

func (c *ItemController) ApiSyncVs() {
	prj_name := c.GetString(":prj")
	branch := c.GetString(":branch")
	prj_obj := models.GetPrjName(prj_name)
	platfm_obj, err := models.GetPlatfm(prj_obj.ID, branch)
	var up_time string
	var ret string
	if err == nil {
		//如果是发布分支
		obj := models.GetReleaseId(platfm_obj.ID)
		old_version := obj.CurVersion
		src_path := fmt.Sprintf("/data/smb/server/%s/%s/", prj_name, branch)
		src_package := src_path + "server.tar.gz"
		cat_cmd := fmt.Sprintf(`cat %sserver/ver/ver.txt | grep code | awk '{print $2}'|sed 's/}//'|sed 's/"//g' | grep -v ^$ |sed 's/,/\//'| sed  '1~2N;s/\r\n//'`, src_path)
		cmd := fmt.Sprintf("rm -rf %sserver ;tar -zxf %s -C %s && %s 2>/dev/null", src_path, src_package, src_path, cat_cmd)
		dict_obj, _ := models.QueryDictKey("RELEASE_HOST")
		release_host := dict_obj.DictVal

		time_cmd := `ls --time-style "+%Y-%m-%d %H:%M:%S" -lct ` + src_package + "|grep -v ^total| awk '{print $6,$7}'"
		up_time = tools.SaltRunArgRet(release_host, "cmd.run", time_cmd, "root")

		ret = tools.SaltRunArgRet(release_host, "cmd.run", cmd, "root")

		//更新发布信息
		obj.CurVersion = ret
		obj.PackageTime = up_time
		models.UpdateRelease(obj.ID, obj)
		//发送邮件通知版本变更
		email_obj, err := models.QueryDictKey("NOTICE_EMAIL")
		if err !=nil{
			fmt.Println("NOTICE_EMAIL:通知邮箱地址未配置")
		}else{
			send_email:= email_obj.DictVal
			body := fmt.Sprintf("{old_version,   \"%s\"}\n{new_version,  \"%s\"}", old_version, ret)
			tools.SendMail(send_email, "【"+prj_name+"】版本变更", body, "")
		}

	} else {
		//其他分支
		src_path := fmt.Sprintf("/data/smb/server/%s/%s/", prj_name, branch)
		src_package := src_path + "server.tar.gz"
		cat_cmd := fmt.Sprintf(`cat %sserver/ver/ver.txt | grep code | awk '{print $2}'|sed 's/}//'|sed 's/"//g' | grep -v ^$ |sed 's/,/\//'| sed  '1~2N;s/\r\n//'`, src_path)
		cmd := fmt.Sprintf("tar -zxf %s -C %s && %s", src_package, src_path, cat_cmd)
		dict_obj, _ := models.QueryDictKey("RELEASE_HOST")
		release_host := dict_obj.DictVal

		time_cmd := `ls --time-style "+%Y-%m-%d %H:%M:%S" -lct ` + src_package + "|grep -v ^total| awk '{print $6,$7}'"
		up_time = tools.SaltRunArgRet(release_host, "cmd.run", time_cmd, "root")
		ret = tools.SaltRunArgRet(release_host, "cmd.run", cmd, "root")
	}

	//更新分支信息
	branch_obj := models.ItemBranch{}
	branch_obj.ReleaseTime = up_time
	branch_obj.CurVersion = ret
	models.UpdateBranchOfName(prj_name, branch, branch_obj)
	c.Data["json"] = ret
	c.ServeJSON()
}

func (c *ItemController) CodeRelease() {
	id, _ := c.GetInt("id", 0)
	obj := models.QueryReleaseOne(id)
	if obj.Status {
		c.Data["json"] = "该版本正在发布任务中，请勿重复发布"
	} else {
		src_path := fmt.Sprintf("/data/smb/server/%s/%s/", obj.Platfm.Prj.PrjName, obj.Platfm.CodeVersion)
		src_package := src_path + "server.tar.gz"
		web_src := src_path + "web_server.tar.gz"
		dest_host := obj.ReleaseHost
		proxy_host := obj.ProxyHost
		var cmd_web string
		var cmd_game string

		if proxy_host != "" {
			//创建中转站命令
			mk_cmd := fmt.Sprintf("mkdir -p /home/admin/server/transfer/%s", obj.Platfm.CodeVersion)
			ssh_cmd := fmt.Sprintf(`ssh admin@%s  "%s"`, proxy_host, mk_cmd)

			//发送到中转站命令
			cmd_web_p := fmt.Sprintf("scp -o 'StrictHostKeyChecking no' %s admin@%s:/home/admin/server/transfer/%s/", web_src, proxy_host, obj.Platfm.CodeVersion)
			cmd_game_p := fmt.Sprintf("scp -o 'StrictHostKeyChecking no' %s admin@%s:/home/admin/server/transfer/%s/", src_package, proxy_host, obj.Platfm.CodeVersion)

			pxy_web_src := fmt.Sprintf("/home/admin/server/transfer/%s/%s", obj.Platfm.CodeVersion, "web_server.tar.gz")
			pxy_src_package := fmt.Sprintf("/home/admin/server/transfer/%s/%s", obj.Platfm.CodeVersion, "server.tar.gz")
			//ssh到中转服务器执行命令
			scp_web := fmt.Sprintf("scp -o 'StrictHostKeyChecking no' %s admin@%s:/home/admin/server/web_release/", pxy_web_src, dest_host)
			scp_game := fmt.Sprintf("scp -o 'StrictHostKeyChecking no' %s admin@%s:/home/admin/server/release/ && echo SUCCESS ||echo FAILED", pxy_src_package, dest_host)
			ssh_scp_web := fmt.Sprintf(`ssh admin@%s  "%s"`, proxy_host, scp_web)
			ssh_scp_game := fmt.Sprintf(`ssh admin@%s  "%s"`, proxy_host, scp_game)

			cmd_web = fmt.Sprintf(`%s && %s && %s`, ssh_cmd, cmd_web_p, ssh_scp_web)
			cmd_game = fmt.Sprintf(`%s && %s`, cmd_game_p, ssh_scp_game)

		} else {
			cmd_web = fmt.Sprintf("scp -o 'StrictHostKeyChecking no' %s admin@%s:/home/admin/server/web_release/", web_src, dest_host)
			cmd_game = fmt.Sprintf("scp -o 'StrictHostKeyChecking no' %s admin@%s:/home/admin/server/release/ && echo SUCCESS ||echo FAILED", src_package, dest_host)
		}

		if dest_host != "" {

			dict_obj, _ := models.QueryDictKey("RELEASE_HOST")
			release_host := dict_obj.DictVal

			// 添加异步任务
			taskName := "task.CodeRelease"
			cli := tasks.Client()
			asyncResult, err := cli.Delay(taskName, release_host, cmd_web, cmd_game, obj.ReleaseHost, obj.CurVersion, id)

			if err != nil {
				panic(err)
			}
			if err != nil {
				c.Data["json"] = "发布失败，请联系管理员"
			} else {
				c.Data["json"] = "发布中:" + asyncResult.TaskID
			}

			//添加任务记录
			tk := models.LogTask{}
			cur_user := c.GetSession("cur_user")
			tk.UserName = cur_user.(string)
			tk.TaskName = fmt.Sprintf("版本发布：%s---%s", obj.Platfm.Prj.PrjName, obj.Platfm.PlatfmName)
			tk.Status = "PENDING"
			tk.TaskId = asyncResult.TaskID
			models.AddTask(tk)
			obj.Status = true
			models.UpdateRelease(id, obj)
		} else {
			c.Data["json"] = "发布IP不能为空"
		}
	}
	c.ServeJSON()

}

func (c *ItemController) CodeHotUp() {
	id, _ := c.GetInt("id", 0)
	hot_file := c.GetString("hot_file")
	hot_file_path := c.GetString("hot_file_path")
	f, h, err := c.GetFile("upload_file")

	obj := models.QueryReleaseOne(id)
	//获取发布平台IP
	release_obj, _ := models.QueryDictKey("RELEASE_HOST")
	release_host := release_obj.DictVal

	//获取运维管理平台IP
	dict_obj, _ := models.QueryDictKey("MASTER_HOST")
	dest_host := dict_obj.DictVal

	//不管热更目录存在与否，创建热更目录
	hot_file_dest_path := fmt.Sprintf("/data/hot_file/%s/%s/", obj.Platfm.Prj.PrjName, obj.Platfm.CodeVersion)
	mkdir_cmd := fmt.Sprintf(`ssh -p 15677 admin@%s  "mkdir -p %s"`, dest_host, hot_file_dest_path)

	var ret string
	if err == nil {
		defer f.Close()
		//获取当前项目路径
		dir, _ := os.Getwd()

		//上传文件保存路径
		save_path := fmt.Sprintf("static/upload/ebin/%s/%s/", obj.Platfm.Prj.PrjName, obj.Platfm.CodeVersion)
		save_path_abs := path.Join(dir, save_path)

		//创建路径
		mk_cmd := fmt.Sprintf("mkdir -p %s", save_path_abs)
		_ = tools.SaltRunArgRet(release_host, "cmd.run", mk_cmd, "root")

		//保存文件
		save_to_file := path.Join(save_path_abs, h.Filename)
		c.SaveToFile("upload_file", save_to_file)

		//scp热更文件
		hot_file_send := fmt.Sprintf("scp -P 15677 -o 'StrictHostKeyChecking no' %s admin@%s:%s && echo SUCCESS ||echo FAILED", save_to_file, dest_host, hot_file_dest_path)

		cmd := fmt.Sprintf("%s && %s", mkdir_cmd, hot_file_send)
		ret = tools.SaltRunArgRet(release_host, "cmd.run", cmd, "root")
	}

	if hot_file != "" {
		src_path := fmt.Sprintf("/data/smb/server/%s/%s/server/%s", obj.Platfm.Prj.PrjName, obj.Platfm.CodeVersion, hot_file_path)
		var hot_file_str string

		for _, v := range strings.Split(hot_file, ",") {
			hot_file_str += src_path + v + " "
		}

		//scp热更文件
		hot_file_send := fmt.Sprintf("scp -P 15677 -o 'StrictHostKeyChecking no' %s admin@%s:%s && echo SUCCESS ||echo FAILED", hot_file_str, dest_host, hot_file_dest_path)

		//执行热更文件发布
		cmd := fmt.Sprintf("%s && %s", mkdir_cmd, hot_file_send)
		ret = tools.SaltRunArgRet(release_host, "cmd.run", cmd, "root")
		c.Data["json"] = ret
	}

	c.ServeJSON()
}
